<template>
    <div class="header">
        <!-- 折叠按钮 -->
        <div class="collapse-btn" @click="collapseChage">
            <i v-if="!collapse" class="el-icon-s-fold"></i>
            <i v-else class="el-icon-s-unfold"></i>
        </div>
        <div class="logo">后台管理系统</div>
        <div class="header-right">
            <div class="header-user-con">
                <!-- 全屏显示 -->
                <div class="btn-fullscreen" @click="handleFullScreen">
                    <el-tooltip effect="dark" :content="fullscreen?`取消全屏`:`全屏`" placement="bottom">
                        <i class="el-icon-rank"></i>
                    </el-tooltip>
                </div>
                <!-- 消息中心 -->
                <div class="btn-bell">
                    <el-tooltip
                        effect="dark"
                        :content="messageContent"
                        placement="bottom"
                    >
                        <router-link to="/sys-message-list">
                            <i class="el-icon-bell"></i>
                        </router-link>
                    </el-tooltip>
                    <span class="btn-bell-badge" v-if="message"></span>
                </div>
                <!-- 用户头像 -->
                <div class="user-avator">
                    <img :src="headLogo" />
                </div>
                <!-- 用户名下拉菜单 -->
                <el-dropdown class="user-name" trigger="click" @command="handleCommand">
                    <span class="el-dropdown-link">
                        {{username}}
                        <i class="el-icon-caret-bottom"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item divided command="userInfo">个人信息</el-dropdown-item>
                        <el-dropdown-item divided command="updatePwd">更改密码</el-dropdown-item>
                        <el-dropdown-item divided command="loginout">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form" :rules="rules" label-width="70px">
                <el-form-item label="登陆名" prop="loginName" >
                    <el-input v-model="form.loginName" disabled></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="userName">
                    <el-input v-model="form.userName"></el-input>
                </el-form-item>
                <el-form-item label="头像">
                    <el-upload
                            ref="upload"
                            class="avatar-uploader"
                            action=""
                            :http-request="fileUpload"
                            :show-file-list="false"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="form.headLogo" :src="form.headLogo" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="编辑" :visible.sync="editVisiblePwd" width="50%">
            <el-form ref="pwdForm" :model="pwdForm" :rules="rules" label-width="70px">
                <el-form-item label="原密码" prop="formerPassword">
                    <el-input type="password" v-model="pwdForm.formerPassword" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="pwdForm.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPassword">
                    <el-input type="password" v-model="pwdForm.checkPassword" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisiblePwd = false">取 消</el-button>
                <el-button type="primary" @click="savePwdEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import bus from '../common/bus';
import { sysUserInfo,sysUserCheckPassword,updateSysUserPassword,updateSysUserBasic } from '../../api/sysUser';
import { sysMessageCountNum } from '../../api/sysMessage';

import { fileUpload } from '../../api/uploadFile';

export default {
    data() {
        let validateFormerPassword = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                sysUserCheckPassword({password:value}).then(res => {
                    if (res.code != 0) {
                        callback(new Error(res.msg));
                    } else {
                        callback();
                    }
                });
            }
        };
        let validatePassword = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                if (this.pwdForm.checkPassword !== '') {
                    this.$refs.pwdForm.validateField('checkPassword');
                }
                callback();
            }
        };
        let validateCheckPassword = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.pwdForm.password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            headLogo: localStorage.getItem('headLogo'),
            collapse: false,
            fullscreen: false,
            name: 'linxin',
            message: 0,
            messageContent:'',
            editVisible: false,
            editVisiblePwd:false,
            activeName: 'second',
            form: {
                loginName:'',
                userName:'',
                headLogo:''
            },
            pwdForm:{
                formerPassword:'',
                password:'',
                checkPassword:''
            },
            rules: {
                userName: [
                    { required: true, message: '请输入名称', trigger: 'blur' }
                ],
                formerPassword: [
                    { validator: validateFormerPassword, trigger: 'blur' }
                ],
                password: [
                    { validator: validatePassword, trigger: 'blur' }
                ],
                checkPassword: [
                    { validator: validateCheckPassword, trigger: 'blur' }
                ]
            }
        };
    },
    computed: {
        username() {
            let username = localStorage.getItem('ms_username');
            return username ? username : this.name;
        }
    },
    created(){
       /* sysMessageCountNum().then(res => {
            // 消息
            this.message = res.countNum;
            //this.messageContent = res.countNum > 0 ? `有`+res.countNum+`条未读消息`:`消息中心`
            this.$set(this, 'messageContent', res.countNum > 0 ? `有`+res.countNum+`条未读消息`:`消息中心`);
        });*/

        /*let userId = localStorage.getItem('userId');
        if (userId != null && userId != "") {
            this.socketApi.createWebSocket();
            this.socketApi.getSock(this.getConfigResult);
        }*/
    },
    methods: {
        // 用户名下拉菜单选择事件
        handleCommand(command) {
            if (command == 'loginout') {
                let userId = localStorage.getItem('userId');
                localStorage.removeItem('ms_username');
                localStorage.removeItem('userId');
                localStorage.removeItem('token');
                // this.socketApi.sendSock({type:"3",data:userId}, this.getConfigResult);                // 发送退出命令
                this.$router.push('/login');
            }
            if (command == 'userInfo') {
                sysUserInfo().then(res => {
                    this.form.id = res.sysUser.id;
                    this.form.loginName = res.sysUser.loginName;
                    this.form.userName = res.sysUser.userName;
                    this.form.headLogo = res.sysUser.headLogo;
                });
                this.editVisible = true;
                this.$nextTick(()=>{
                    this.$refs['form'].clearValidate();
                })
            }
            if (command == 'updatePwd') {
                this.editVisiblePwd = true;
                this.$nextTick(()=>{
                    this.$refs['pwdForm'].clearValidate();
                })
            }
        },
        getConfigResult(res){
            if (res.type != null && res.type != "" && res.type == "1") {
                // 有消息待查看
                this.$notify({
                    title: '提示',
                    message: res.data,
                    duration: 0
                });
                // 需要刷新消息数，延迟刷新
                sysMessageCountNum().then(res => {
                    // 消息
                    this.message = res.countNum;
                    this.$set(this, 'messageContent', res.countNum > 0 ? `有`+res.countNum+`条未读消息`:`消息中心`);
                });
            }
        },
        // 保存编辑
        saveEdit() {
            this.$refs['form'].validate((valid) => {
                if (!valid) {
                    console.log('error submit!!');
                    return false;
                }
                updateSysUserBasic(this.form).then(res => {
                    if (res.code == 0) {
                        this.editVisible = false;
                        this.$message.success(`修改成功`);
                        this.getData();
                    } else {
                        this.$message.error(res.msg);
                        return false;
                    }
                });
            });
        },
        savePwdEdit() {
            this.$refs['pwdForm'].validate((valid) => {
                if (!valid) {
                    console.log('error submit!!');
                    return false;
                }
                updateSysUserPassword({password:this.pwdForm.password}).then(res => {
                    if (res.code == 0) {
                        this.editVisiblePwd = false;
                        this.$message.success(`修改成功`);
                        // 修改密码后需要直接弹出吗
                        this.getData();
                    } else {
                        this.$message.error(res.msg);
                        return false;
                    }
                });
            });
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        fileUpload(file){
            let _this = this;
            return fileUpload(file).then(res => {
                _this.form.headLogo = res.data[0]
                _this.$refs.upload.clearFiles();//清空
            });
        },
        // 侧边栏折叠
        collapseChage() {
            this.collapse = !this.collapse;
            bus.$emit('collapse', this.collapse);
        },
        // 全屏事件
        handleFullScreen() {
            let element = document.documentElement;
            if (this.fullscreen) {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.webkitCancelFullScreen) {
                    document.webkitCancelFullScreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                }
            } else {
                if (element.requestFullscreen) {
                    element.requestFullscreen();
                } else if (element.webkitRequestFullScreen) {
                    element.webkitRequestFullScreen();
                } else if (element.mozRequestFullScreen) {
                    element.mozRequestFullScreen();
                } else if (element.msRequestFullscreen) {
                    // IE11
                    element.msRequestFullscreen();
                }
            }
            this.fullscreen = !this.fullscreen;
        }
    },
    mounted() {
        if (document.body.clientWidth < 1500) {
            this.collapseChage();
        }
    }
};
</script>
<style scoped>
.header {
    position: relative;
    box-sizing: border-box;
    width: 100%;
    height: 70px;
    font-size: 22px;
    color: #fff;
}
.collapse-btn {
    float: left;
    padding: 0 21px;
    cursor: pointer;
    line-height: 70px;
}
.header .logo {
    float: left;
    width: 250px;
    line-height: 70px;
}
.header-right {
    float: right;
    padding-right: 50px;
}
.header-user-con {
    display: flex;
    height: 70px;
    align-items: center;
}
.btn-fullscreen {
    transform: rotate(45deg);
    margin-right: 5px;
    font-size: 24px;
}
.btn-bell,
.btn-fullscreen {
    position: relative;
    width: 30px;
    height: 30px;
    text-align: center;
    border-radius: 15px;
    cursor: pointer;
}
.btn-bell-badge {
    position: absolute;
    right: 0;
    top: -2px;
    width: 8px;
    height: 8px;
    border-radius: 4px;
    background: #f56c6c;
    color: #fff;
}
.btn-bell .el-icon-bell {
    color: #fff;
}
.user-name {
    margin-left: 10px;
}
.user-avator {
    margin-left: 20px;
}
.user-avator img {
    display: block;
    width: 40px;
    height: 40px;
    border-radius: 50%;
}
.el-dropdown-link {
    color: #fff;
    cursor: pointer;
}
.el-dropdown-menu__item {
    text-align: center;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
